<template>
  <div id="colorBlock_1">
    <!--未完成签到表格-->
    <el-table
        v-loading="loading"
        stripe
        :data="signInRecordTable.filter((v) => this.leach(v))"
        style="width: 98%;position: relative;top:5px;left: 1%;">
      <el-table-column
          prop="endTime"
          label="结束时间"
          width="150">
        <template slot-scope="scope">
          <span>
            {{format(scope.row.endTime)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
          prop="groupName"
          label="发布群组">
      </el-table-column>

      <el-table-column
          fixed="right"
          label="立即签到"
          width="180">
        <template slot-scope="scope">
          <el-button
              @click="signInDialog(scope.row)"
              style="width: 130px;"
              type="primary"
              icon="el-icon-finished"
              size="medium" plain round>
            {{ buttonText(scope.row.signInType) }}</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--投票签到对话框-->
    <el-dialog
        title="投票签到"
        :visible.sync="voteDialogVisible"
        style="max-width: 800px;margin:auto;"
        width="70%"
        >
<!--      :before-close="handleClose"-->
      <div style="text-align: center">
        <span style="width: 100%;font-size: 20px;font-weight:bold;">{{this.signingForm.voteQuestion}}</span>
      </div>

      <el-form
          :model="signingForm"
          status-icon
          style="display:block;margin: auto;"
          :rules="rules"
          ref="signingForm"
          label-width="10%"
          class="demo-ruleForm">

        <el-form-item  prop="voteOption" style="margin-top: 20px;display: flex;">
          <el-radio-group v-model="signingForm.voteOption" style="line-height: 50px;">
            <el-radio
                style="width: 100%;"
                label="0">{{ this.signingForm.voteOption1 }}</el-radio>

            <el-radio
                style="width: 100%;"
                label="1">{{ this.signingForm.voteOption2}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item class="buttons" >
          <el-button type="primary" @click="submitForm()">提交</el-button>
          <el-button @click="voteDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <!--定位签到失败的对话框-->
    <el-dialog
        v-loading="loading"
        title="距离签到点过远，请点击重新定位"
        :visible.sync="locationDialogVisible"
        style="max-width: 800px;margin:auto;text-align: center;"
        width="70%"
        >
<!--      :before-close="handleClose"-->
      <div style="height: 320px;width: 300px;margin: auto">
        <div style="
        background-color: rgba(178,238,213,0.8);
        position: absolute;
        height: 300px;
        width: 300px;
        border:2px solid rgba(203,227,236,0.3);
        transform:rotate(120deg);
        border-radius: 50% 80% 40% 90%"></div>

        <div style="
        background-color: rgba(112,209,220,0.3);
        position: absolute;
        margin-left: 50px;
        margin-top: 50px;
        height: 200px;
        width: 200px;
        border:1px solid rgba(97,197,234,0.2);
        transform:rotate(160deg);
        border-radius: 50% 90% 40% 80%"></div>

        <div style="
        background-color: rgba(109,202,236,0.4);
        position: absolute;
        margin-left: 75px;
        margin-top: 75px;
        height: 150px;
        width: 150px;
        border:1px solid rgba(178,238,213,0.3);
        transform:rotate(60deg);
        border-radius: 30% 50% 40% 50%"></div>

        <el-button
            style="
            position: absolute;
            margin-left: -50px;
            margin-top: 100px;
            font-size: 20px;
            width: 100px;
            height: 100px;
            border-radius: 100px"
            @click="getMap"
            type="primary" plain round>
          {{(this.distance).toString().replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')}} m
<!--          <div >获取</div>-->
<!--          <div>定位</div>-->
        </el-button>

        </div>

    </el-dialog>

    <!--扫码签到对话框-->
    <el-dialog
        title="扫码签到"
        :visible.sync="qrcodeDialogVisible"
        style="max-width: 800px;margin:auto;"
        width="90%"
        >
<!--      :before-close="handleClose"-->
      <div style="height: 350px;width: 400px;margin: 20px auto auto;overflow: hidden">
        <vue-qrcode @listen="qrcodeSignIn" />
      </div>

    </el-dialog>

    <!--签到成功的签到提示-->
    <el-dialog
        title="签到提示"
        :visible.sync="successDialogVisible"
        style="max-width: 800px;margin:auto;"
        width="70%">
      <el-result icon="success" title="签到成功" subTitle="可在已完成中查看结果">
        <template slot="extra">
          <el-button @click="successDialogVisible = false" type="primary" size="medium">返回</el-button>
        </template>
      </el-result>
    </el-dialog>

    <!--签到失败的对话框-->
    <el-dialog
        title="签到提示"
        :visible.sync="failDialogVisible"
        style="max-width: 800px;margin:auto;"
        width="70%">
      <el-result icon="error" title="签到失败" subTitle="签到时间已过！">
        <template slot="extra">
          <el-button @click="failDialogVisible = false" type="primary" size="medium">返回</el-button>
        </template>
      </el-result>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/utils/request";
import moment from "moment";
import qrcode from '@/components/qrcode.vue';

export default {
  name: "Unfinished",
  //组件注册
  components: {
    'vue-qrcode': qrcode,
  },
  data() {
    let self=this;
    return {
      signingForm: {//投票签到表单
        voteQuestion:'',
        voteOption:'',
        voteOption1:'',
        voteOption2:'',
        detail:{}
      },
      rules: {//投票签到表单验证
        voteOption:[{ required: true, message: '请选择要提交的选项', trigger: 'change' }],
      },
      signInRecordTable: [],//未完成的签到表数据数组
      studentRecord:{//学生签到数据表单
        user_id:'',
        user_name:'',
        school_number:'',
        sign_in_status:'',
        sign_in_time:[]//
      },
      loginId:sessionStorage.getItem("loginId"),//登录信息
      successDialogVisible: false,//签到成功对话框标记
      failDialogVisible: false,//签到失败对话框标记
      voteDialogVisible: false,//投票签到对话框标记
      locationDialogVisible: false,//定位签到对话框标记
      qrcodeDialogVisible: false,//扫码签到对话框标记
      distance:'',//定位位置于签到点位置的距离
      lng:'',//签到点经度
      lat:'',//签到点纬度

      localLng:'',//定位点经度
      localLat:'',//定位点纬度

      loading:false,//加载显示标记

    }
  },
  //初始化
  created() {
    this.load()
  },
  mounted(){
  },
  methods: {
    //数据加载
    load(){
      request.get("/published/unfinished/"+this.loginId).then(res =>{
        console.log(res)
        this.signInRecordTable=res
      })
    },
    //数据展示过滤条件，只显示未完成签到
    leach(row) {
      // if(this.isPassed(row)){ return false } //

      var result=JSON.parse(row.result.substring(10,(row.result).length-1))
      for(var i=0;i<result.length; i++){
        if(result[i].user_id===this.loginId){
          return result[i].sign_in_status === 0;
        }
      }
    },
    //时间格式转换
    format(startTime){
      return startTime[0]+'-'+
          (startTime[1]<10?'0'+startTime[1]:startTime[1])+'-'+
          (startTime[2]<10?'0'+startTime[2]:startTime[2])+' '+
          (startTime[3]<10?'0'+startTime[3]:startTime[3])+':'+
          (startTime[4]<10?'0'+startTime[4]:startTime[4])+':'+
          (startTime[5]<10?'0'+startTime[5]:startTime[5])
    },
    //根据当前时间生成对应格式时间
    gotTime(){
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();

      return yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    },
    //根据签到类型展示不同的签到按钮
    buttonText(signInType){
      switch(signInType){
        case 'click':return '点击签到';
        case 'vote':return '投票签到';
        case 'location':return '定位签到';
        case 'qrcode':return '扫码签到';
      }
    },
    //根据签到类型为不同按钮赋予响应
    signInDialog(row){
      switch (row.signInType){
        case 'click' : this.sendRecord(row,0); break;
        case 'vote' : this.voteSignIn(row); break;
        case 'location' : this.locationSignIn(row); break;
        case 'qrcode' : this.qrcodeDialog(row); break;
      }
    },
    //初始化投票对话框并复制该表数据
    voteSignIn(row){
      this.signingForm.voteQuestion=row.voteQuestion;
      this.signingForm.voteOption1=row.voteOption.split("+")[0];
      this.signingForm.voteOption2=row.voteOption.split("+")[1];
      this.signingForm.detail=row
      this.voteDialogVisible=true;
    },
    //初始化学生签到表单并打开扫码对话框
    qrcodeDialog(row){
      if(this.isPassed(row)){
        this.failDialogVisible = true;
      }else{
        var result=JSON.parse(row.result.substring(10,(row.result).length-1))
        var flag=true

        for(var i=0;i<result.length; i++){
          if(result[i].user_id===this.loginId){
            this.studentRecord=result[i]
            this.studentRecord.sign_in_status=1
            flag=false
          }
        }
        if(flag){
          this.$message({
            message: "签到失败",
            type: 'error'
          });
        }else{
          this.qrcodeDialogVisible=true;
        }
      }

    },
    //响应扫码组件，装填签到表单并提交
    qrcodeSignIn(signInId){
      this.studentRecord.sign_in_time=this.gotTime()
      request.post("/published/sign/"+signInId+"/"+0,this.studentRecord).then(res =>{
        if(res){
          this.successDialogVisible = true;
          if(this.qrcodeDialogVisible === true){
            this.qrcodeDialogVisible=false;
          }
          this.load()
          return null
        }else{
          this.$message({
            message: "签到失败",
            type: 'error'
          });
        }
      })
      this.load()
    },
    //计算两个经纬度之间的距离
    getDiscount(lat1,lng1,lat2,lng2){
      // console.log(paramObj)
      var lng1 = lng1
      var lat1 = lat1
      var lng2 = lng2
      var lat2 = lat2
      var radLat1 = lat1*Math.PI / 180.0;
      var radLat2 = lat2*Math.PI / 180.0;
      var a = radLat1 - radLat2;
      var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
          Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
      s = s *6378.137 ;// EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000;
      s = s * 1000
      if (isNaN(s)) {
        return 0+'m';
      }
      // if (s > 1000) {
      //   //    大于1000米时
      //   s = Math.floor(s/1000 * 100) / 100;
      //   s = s*1000 + 'm'
      // } else {
      //   //    小于1000米直接返回
      //   s = s + 'm'
      // }
      return s;
    },
    //签到表单初始化并获取定位
    locationSignIn(row){
      this.signingForm.detail=row
      this.lat=row.userLocation.split(',')[1]+''
      this.lng=row.userLocation.split(',')[0]+''
      this.getMap()

    },
    //百度转高德经纬度
    // bMapTransQQMap(lat,lng) {
    //   var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    //   var x = lng - 0.0065;
    //   var y = lat - 0.006;
    //   var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    //   var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    //   this.getLongitude = z * Math.cos(theta);
    //   this.getLatitude=z * Math.sin(theta)
    // },
    //高德地图获取定位，若签到失败则展示重定位对话框
    getMap () {
      this.loading=true

      var that = this
      // ⽣成地图
      var map = new window.AMap.Map('container', {
        resizeEnable: true,//是否监控地图容器尺寸变化
        zoom: 11,
        showIndoorMap: false, // 是否在有⽮量底图的时候⾃动展⽰室内地图，PC默认true,移动端默认false
        dragEnable: true, // 地图是否可通过⿏标拖拽平移，默认为true
        keyboardEnable: false, // 地图是否可通过键盘控制，默认为true
        doubleClickZoom: true, // 地图是否可通过双击⿏标放⼤地图，默认为true
        zoomEnable: true, // 地图是否可缩放，默认值为true
        rotateEnable: false, // 地图是否可旋转，3D视图默认为true，2D视图默认false
        viewMode: '3D'
      })
      // 获取到当前位置的定位
      AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
          // 是否使⽤⾼精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：⽆穷⼤
          timeout: 10000,
          // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
          buttonOffset: new AMap.Pixel(200, 200),
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true,
          //  定位按钮的排放位置,  RB表⽰右下
          buttonPosition: 'RB'
        })
        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', onComplete)
        AMap.event.addListener(geolocation, 'error', onError)
        function onComplete (data) {
          // data是具体的定位信息
          console.log('data是具体的定位信息', data)
          that.loading=false
          // 这⾥使⽤that⽽不是this，如果使⽤this，则⽆法在其他地⽅获取到这⾥的经纬度
          that.localLng = data.position.lng
          that.localLat = data.position.lat

          // alert('布置：'+that.lat+','+that.lng+',\n当前：'+that.localLat+','+that.localLng)
          //根据经纬度计算经当前定位与签到点之间的距离
          that.distance=that.getDiscount(that.lat,that.lng,that.localLat,that.localLng)

          if(that.distance<50){ //定位距离与规定点大于50时签到失败
            that.sendRecord(that.signingForm.detail,0)
          }else{
            that.locationDialogVisible = true;
          }

        }
        function onError (data) {
          // 定位出错
          console.log('定位失败')
        }
      })
      that.maps = map
    },
    //百度地图 备用
    locating(){
      var _this = this;
      if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            //locationSuccess 获取成功的话
            function(position) {
              _this.getLongitude = position.coords.longitude;
              _this.getLatitude = position.coords.latitude;

              // _this.lng= _this.getLongitude
              // _this.lat= _this.getLatitude
              // _this.bMapTransQQMap(_this.getLatitude,_this.getLongitude)
              alert('布置：'+_this.lat+','+_this.lng+',\n当前：'+_this.getLatitude+','+_this.getLongitude)

              _this.distance=_this.getDiscount(_this.lat,_this.lng,_this.getLatitude,_this.getLongitude)

              if(_this.distance<50){ //定位距离与规定点大于50时签到失败
                _this.sendRecord(_this.signingForm.detail,0)
              }else{
                _this.locationDialogVisible = true;
              }

            },
            //locationError  获取失败的话
            function(error) {
              var errorType = ['您拒绝共享位置信息', '获取不到位置信息', '获取位置信息超时'];
              alert(errorType[error.code - 1]);
            }
        );
      }
    },
    //提交投票签到表单
    submitForm() {
      this.sendRecord(this.signingForm.detail,this.signingForm.voteOption)
    },
    //装填签到表单并提交签到请求
    sendRecord(row,option){
      if(this.isPassed(row)){
        this.failDialogVisible = true;
      }else{
        var result=JSON.parse(row.result.substring(10,(row.result).length-1))
        var flag=true

        for(var i=0;i<result.length; i++){
          if(result[i].user_id===this.loginId){
            this.studentRecord=result[i]
            flag=false
            this.studentRecord.sign_in_status=1
            this.studentRecord.sign_in_time=this.gotTime()

            request.post("/published/sign/"+row.signInId+"/"+option,this.studentRecord).then(res =>{
              if(res){
                this.successDialogVisible = true;
                if(this.voteDialogVisible === true){
                  this.voteDialogVisible=false;
                }
                this.load()
                return null
              }else{
                this.$message({
                  message: "签到失败",
                  type: 'error'
                });
              }
            })

          }
        }
        if(flag){//找不到id则签到失败
          this.$message({
            message: "签到失败",
            type: 'error'
          });
        }
      }
      this.load()
    },
    //根据结束时间判断签到是否已过期
    isPassed(row){
      row.endTime[1]-=1
      let end = new Date(moment(row.endTime).format('yyyy-MM-DD HH:mm:ss')).getTime();
      return end < Date.now();
    },
  },

}
</script>

<style scoped>
#colorBlock_1{
  background-color: rgba(255, 255, 255, 0.8);
  max-width: 550px;
  min-width: 400px;
  min-height: 700px;
  width: 99%;
  margin: auto;
  margin-top: 10px;
  margin-bottom: 7%;
  border-radius: 10px;
  box-shadow: 2px 2px 3px rgba(192, 197, 194, 0.3);
}
.buttons{
  width: 100%;
  margin-top: 10%;
}
.buttons .el-button{
  width: 35%;
  margin-left: 5%;
}
.move{
  /*transform: rotate(20deg);*/
}
</style>